package com.lg.videos.controller;

import com.lg.videos.entity.to.Thumbnail;
import lombok.SneakyThrows;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.FrameGrabber;
import org.bytedeco.javacv.Java2DFrameConverter;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/thumbnail")
public class ThumbnailController {

    @SneakyThrows
    @GetMapping("parse")
    public void parse(String videoPath){
        FFmpegFrameGrabber ff = FFmpegFrameGrabber.createDefault(videoPath);
        ff.start();
        System.out.println(ff.getAudioCodec());
        System.out.println(ff.getVideoCodec());
        ff.stop();
    }

    /**
     * 截取视频第  某某  帧的图片
     * @return 图片的相对路径 例：pic/1.png
     * @throws FrameGrabber.Exception
     */
    @GetMapping("/create")
    public String create(@RequestBody Thumbnail thumbnail) throws FrameGrabber.Exception {
        File targetFile = new File(thumbnail.getFilePath());
        if (!targetFile.exists())
            return null;
        String fileName = targetFile.getName().substring(0,targetFile.getName().lastIndexOf("."));
        String pngPath = "";
        FFmpegFrameGrabber ff = FFmpegFrameGrabber.createDefault(thumbnail.getFilePath());
        ff.start();


        int ffLength = ff.getLengthInFrames();
        Frame f;
        int i = 0;
        while (i < ffLength) {
            f = ff.grabImage();
            //截取第6帧
            if((i>=thumbnail.getTargetFrame()) &&  (f.image != null)){
                //生成图片的相对路径 例如：pic/uuid.png
                pngPath = getPngPath(fileName);
                //执行截图并放入指定位置
                doExecuteFrame(f, thumbnail.getOutPutDir()+pngPath);
                break;
            }
            i++;
        }
        ff.stop();

        return pngPath;
    }

    /**
     * 生成图片的相对路径
     * @return 图片的相对路径 例：pic/1.png
     */
    private String getPngPath(String name){
        return  "/"+name+"_"+getUUID()+".png";
    }


    /**
     * 生成唯一的uuid
     * @return uuid
     */
    private  String getUUID(){
        return UUID.randomUUID().toString().replace("-","");
    }


    /**
     * 截取缩略图
     * @param f Frame
     * @param targerFilePath:封面图片存放路径
     */
    private  void doExecuteFrame(Frame f, String targerFilePath) {
        String imagemat = "png";
        if (null == f || null == f.image) {
            return;
        }
        Java2DFrameConverter converter = new Java2DFrameConverter();
        BufferedImage bi = converter.getBufferedImage(f);
        File output = new File(targerFilePath);
        try {
            ImageIO.write(bi, imagemat, output);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
